package com.xpec.cipher.algorithm;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 * ARC4加密算法
 * @author shangyong
 *
 */
public class RC4 
{
	private Key key = null;
	
	public Cipher encryptCipher;
	
	public Cipher decryptCipher;

	public RC4(byte[] byteKey)
	{
		try {
			key = toKey(byteKey);
			encryptCipher = Cipher.getInstance("RC4");
			encryptCipher.init(Cipher.ENCRYPT_MODE, key);
			decryptCipher = Cipher.getInstance("RC4");
			decryptCipher.init(Cipher.DECRYPT_MODE, key);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 加密
	 * @param data
	 * @param key
	 * @return
	 */
	public byte[] encrypt(byte[] data, byte[] byteKey)
	{
		try
		{
			byte[] result = encryptCipher.doFinal(data);
			return result;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new IllegalStateException("RC4 encrypt is illegal");
		}
	}

	public byte[] decrypt(byte[] data, byte[] byteKey)
	{
		try
		{
			byte[] result = decryptCipher.doFinal(data);
			return result;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new IllegalStateException("RC4 encrypt is illegal");
		}
	}

	private Key toKey(byte[] byteKey)
	{
		try
		{
			SecretKeySpec keySpec = new SecretKeySpec(byteKey, "RC4");
			return keySpec;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			
			throw new IllegalStateException("RC4 Key is illegal");
		}
	}
}
